<?php

namespace app\common\model\search;

use app\common\model\PatientInfo as PatientInfoModel;
use app\common\model\CollectClass as CollectClassModel;



trait CollectCaseSearch
{
    //患者姓名
    public function searchNameAttr($query, $value, $data)
    {
        $ids = (new PatientInfoModel)->where('name', 'like', $value)->field('id')->select()->toArray();

        $pids = [];
        foreach ($ids as $key => $val)
        {
            $pids[] = $val['id'];
        }
        return $query->whereIn('pid', $pids);
    }

    //分组： -1 全部，-2 未分组
    public function searchClassIdAttr($query, $value, $data)
    {

        switch ($value){
            case '-1':
                $result = $query->where([]);
                break;
            case '-2':
                $list = (new CollectClassModel)->where('creator_id', request()->user()->id)->field('patientList')->select()->toArray();
                $ids = [];
                foreach ($list as $key => $val)
                {
                    if (isset($val['patientList']))
                    {
                        foreach ($val['patientList'] as $k1 => $v1)
                        {
                            if (isset($v1['patient_id']))
                            {
                                $ids[] = $v1['patient_id'];
                            }
                        }
                    }    
                }
                $result = $query->whereNotIn('patientId', $ids);
                break;
            default:            
            $list = (new CollectClassModel)->where('xpath', 'like', $value)->field("patientList")->select()->toArray();

            $ids = [];
            foreach ($list as $key => $val) {
                if (isset($val['patientList'])) {
                    foreach ($val['patientList'] as $k1 => $v1) {
                        if (isset($v1['patient_id'])) {
                            $ids[] = $v1['patient_id'];
                        }
                    }
                }
            }
            $result = $query->whereIn('patientId', $ids);
        }
        return $result;
    }

    //是否死亡
//    public function searchLiveStatusAttr($query, $value, $data)
//    {
//        $collectList = $this->field('pid')->select()->toArray();
//
//        $collectPids = $this->forIds($collectList, 'pid');
//
//        $patientList = (new PatientInfoModel())->whereIn('id', $collectPids)->where('liveStatus', '=', (string)$value)->field('id')->select()->toArray();
//        $pids = $this->forIds($patientList, 'id');
//
//        return $query->whereIn('pid', $pids);
//    }

    //遍历多个id
    private function forIds($array, $field)
    {
        $ids = [];
        foreach ($array as $k => $v)
        {
            $ids[] = $v[$field];
        }
        return $ids;
    }
}